package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.data.entity.Good;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.TimeUtil;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 文件下载Servlet
 * @author Kai
 */
@WebServlet(name = "FileDownloadServlet", urlPatterns = "/file-download.jsp")
public class FileDownloadServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String target = req.getParameter("target");
        if (target == null) {
            resp.sendRedirect("/");
            return;
        }

        ServletOutputStream stream = resp.getOutputStream();
        String time = TimeUtil.getTimeFormat(System.currentTimeMillis());
        String downloadName = "download.csv";


        if (target.equalsIgnoreCase("user")) {
            downloadName = "market_user_" + time + ".csv";
        } else if (target.equalsIgnoreCase("good")) {
            downloadName = "market_good_" + time + ".csv";
        }
        resp.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
        resp.setContentType("application/x-download;charset=UTF-8");
        writeToStream(target, stream);
        stream.close();
        resp.sendRedirect("/");
    }

    private void writeToStream(String type, ServletOutputStream stream) throws IOException {
        if (type.equalsIgnoreCase("user")) {
            List<User> users = userRepository.query();

            for (User user : users) {
                String result = user.getRow() + "," +
                        user.getUsername() + "," +
                        user.getPassword() + "," +
                        user.getRole() + "," +
                        user.getId() + "\n";
                stream.print(result);

            }
            return;
        }
        if (type.equalsIgnoreCase("good")) {
            List<Good> goods = goodRepository.query();
            for (Good good : goods) {
                String result = good.getId() + "," +
                        good.getName() + "," +
                        good.getAmount() + "," +
                        good.getPrice() + "," +
                        good.getState() + "\n";
                stream.print(result);
            }
        }

    }
}
